package com.hcrazy.manchester.app.controllers.seller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hcrazy.manchester.app.form.SellerSearchForm;
import com.hcrazy.manchester.app.pojo.ErrorMsg;
import com.hcrazy.manchester.app.pojo.FoodType;
import com.hcrazy.manchester.app.pojo.PageModel;
import com.hcrazy.manchester.app.pojo.Seller;
import com.hcrazy.manchester.app.pojo.User;
import com.hcrazy.manchester.app.services.FoodTypeService;
import com.hcrazy.manchester.app.services.SellerService;
import com.hcrazy.manchester.app.services.UserService;
import com.hcrazy.manchester.app.utils.Constant;
import com.hcrazy.manchester.app.utils.Log;

@Controller
@RequestMapping("/seller")
public class SellerController {
	
	@Autowired
	private SellerService sellerService;
	
	@Autowired
	private FoodTypeService foodTypeService;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/main",method=RequestMethod.GET)
	public void main(){
		
	}
	
	/**
	 * 跳转新增页面
	 * 初始化页面数据
	 * @param model
	 */
	@RequestMapping(value="/addSeller",method=RequestMethod.GET)
	public void addSeller(Model model){
		setFoodTypes(model);
		//初始化新增对象
		model.addAttribute("seller", new Seller());
	}
	
	/**
	 * 编辑信息内容
	 * @param infoId 信息标识
	 * @param model 数据返回对象
	 * @return
	 */
	@RequestMapping(value="/editSeller",method=RequestMethod.GET)
	public String editSeller(@RequestParam long sellerId,Model model){
		try {
			//初始化对象内容
			addSeller(model);
			//根据id获取信息内容
			Seller seller = sellerService.getSellerById(sellerId);
			//更新返回对象
			model.addAttribute("seller",seller);
		} catch (Exception e) {
			Log.error(e.getMessage(), e);
		}
		return "/seller/addSeller";
	}
	
	/**
	 * 提交信息内容
	 * @param seller
	 * @return
	 */
	@RequestMapping(value="/seller",method=RequestMethod.POST,produces=MediaType.APPLICATION_JSON_VALUE)
    public String addOrUpdateSort(@ModelAttribute("form") Seller seller,
    		HttpServletRequest req,
    		Model model){
		Object object = req.getSession().getAttribute("user");
		if(null == object || !(object instanceof User)){
			model.addAttribute("message", "请首先登录系统！");
			return "/seller/failed";
		}
		User user = (User)object;
		seller.setUserId(user.getUserId());
		try {
			sellerService.addOrUpdateSeller(seller);
		} catch (Exception e) {
			Log.error(e.getMessage(), e);
			model.addAttribute("message", e.getMessage());
			return "/seller/failed";
		}
		return "redirect:/seller/seller";
    }
	
	/**
	 * 跳转至功能信息列表页
	 * @param model
	 */
	@RequestMapping(value="/seller",method=RequestMethod.GET)
	public String seller(Model model,HttpServletRequest req){
		
		Object object = req.getSession().getAttribute("user");
		if(null == object || !(object instanceof User)){
			model.addAttribute("message", "请首先登录系统！");
			return "/seller/failed";
		}
		User user = (User)object;
		//根据查询参数获取分页对象：默认第一页、分类参数为0、查询字符串为空
		PageModel pageModel = getAllSellersByUserId(1,0,"",user.getUserId());
		model.addAttribute("pageModel", pageModel);
		
		//初始化分类
		setFoodTypes(model);
		
		//初始化查询对象
		model.addAttribute("searchForm", new SellerSearchForm());
		
		return "/seller/seller";
	}
	
	/**
	 * 查询信息列表
	 * @param form 查询参数form
	 * @param pageNum 当前分页
	 * @param model 请求返回对象
	 * @return
	 */
	@RequestMapping(value="/search_seller",method=RequestMethod.POST)
	public String searchAddress(@ModelAttribute("form") SellerSearchForm form,
			Model model,HttpServletRequest req){
		//是否执行删除操作
		if(form.getSellerId() > 0){
			try {
				sellerService.delSeller(form.getSellerId());
			} catch (Exception e) {
				Log.error(e.getMessage(), e);
			}
		}
		//重置infoId
		form.setSellerId(0);
		
		Object object = req.getSession().getAttribute("user");
		if(null == object || !(object instanceof User)){
			model.addAttribute("message", "请首先登录系统！");
			return "/seller/failed";
		}
		User user = (User)object;
		
		//根据查询参数获取分页对象
		PageModel pageModel = getAllSellersByUserId(form.getPageNum(),form.getFoodType(), form.getSearch(),user.getUserId());
		model.addAttribute("pageModel", pageModel);

		//设置查询类别
		setFoodTypes(model);
		
		//回传查询参数
		model.addAttribute("searchForm",form);
		
		return "/seller/seller";
	}
	
	/**
	 * 查询全部信息列表
	 * @param pageNum
	 * @param sortId
	 * @param search
	 * @return PageModel
	 */
	private PageModel getAllSellersByUserId(int pageNum,int foodType,String search,long userId){
		PageModel model = new PageModel();
		model.setPageNum(pageNum);

		try {
			return sellerService.getSellers(model, search, foodType, userId);
		} catch (Exception e) {
			Log.error(e.getMessage(), e);
			return null;
		}
	}

	private void setFoodTypes(Model model){
		//根据功能码设置分类列表
		try {
			List<FoodType> foodTypes = foodTypeService.getAllFoodTypes();
			model.addAttribute("foodTypes", foodTypes);
		} catch (Exception e) {
			Log.error(e.getMessage(), e);
		}		
	}
	
	
	/**************************************login***************************************************/
	
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public void adminLogin(Model model,@RequestParam(required=false) String url){
		model.addAttribute("url",url);
	}
	
	@RequestMapping(value="/logout",method=RequestMethod.GET)
	public String logout(HttpServletRequest req){
		req.getSession().setAttribute("user", null);
		req.getSession().invalidate();
		
		return "redirect:/seller/login";
	}
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public @ResponseBody Object login(@RequestParam String username,@RequestParam String password,
			@RequestParam String validateCode,Model model,HttpServletRequest req){
		ErrorMsg msg = new ErrorMsg();
		String sessionValidateCode = null == req.getSession().getAttribute("validateCode")?null:req.getSession().getAttribute("validateCode").toString();
		if(!validateCode.equalsIgnoreCase(sessionValidateCode)){
			msg.setCode(Constant.MEMBER_REGISTER_VALIDATECODE);
			msg.setMsg("验证码不正确！");
			return msg;
		}
		try {
			Object result = userService.login(username, password);
			if(null != result && result instanceof User){
				User user = (User)result;
				if(user.getMemberType() != Constant.MEMBER_TYPE_SELLER){
					return new ErrorMsg(Constant.FAILED, "非商业用户！");
				}
				req.getSession().setAttribute("user",result);
			}
			return result;
			
		} catch (Exception e) {
			Log.error(e.getMessage(), e);
		}
		
		return null;
	}
	
	@RequestMapping(value="/register")
	public void register(){
		
	}
	
	
}
